﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TwoFactorAuthApi.Model;
using TwoFactorAuthNet;

namespace TwoFactorAuthApi.Controllers
{
    [ApiController]
    [Route("api/twoAuth")]
    public class TwoAuthController : ControllerBase
    {
        private readonly string issuer = "MyCompany";
        [Route("getSecret")]
        [HttpGet]
        public string GetSecret()
        {
            var tfa = new TwoFactorAuth(issuer);
            // Though the default is an 80 bits secret (for backwards compatibility reasons) we 
            // recommend creating 160+ bits secrets (see RFC 4226 - Algorithm Requirements)
            var secret = tfa.CreateSecret(160);
            return secret;
        }

        [Route("getQrCodeImage")]
        [HttpGet]
        public string GetQrCodeImage([FromQuery] GetQrCodeImageInput input)
        {
            var tfa = new TwoFactorAuth(issuer);
            // Display QR code to user
            var url = tfa.GetQrCodeImageAsDataUri(input.Label, input.Secret);
            return $"<img src=\"{url}\" >";
        }

        [Route("verifyCode")]
        [HttpPost]
        public IActionResult VerifyCode([FromBody] VerifyCodeInput input)
        {
            var tfa = new TwoFactorAuth(issuer);
            // Verify code
            var result = tfa.VerifyCode(input.Secret, input.Code);
            if (result)
            {
                return Ok();
            }
            else
            {
                return new StatusCodeResult(400);
            }
        }
    }
}
